package com.jetwinner.webfast.module.bigapp.dao.impl;

import com.jetwinner.webfast.dao.support.DynamicQueryBuilder;
import com.jetwinner.webfast.dao.support.FastJdbcDaoSupport;
import com.jetwinner.webfast.kernel.dao.support.OrderBy;
import com.jetwinner.webfast.kernel.exception.RuntimeGoingException;
import com.jetwinner.webfast.module.bigapp.dao.AppGroupMemberDao;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xulixin
 */
@Repository
public class AppGroupMemberDaoImpl extends FastJdbcDaoSupport implements AppGroupMemberDao {

    private final String TABLE_NAME = "big_app_group_member";

    @Override
    public void addMember(Map<String, Object> fields) {
        int affected = insertMap(TABLE_NAME, fields);
        if (affected <= 0) {
            throw new RuntimeGoingException("Insert GroupMember error.");
        }
    }

    @Override
    public int searchMembersCount(Map<String, Object> conditions) {
        DynamicQueryBuilder builder = this.createGroupMemberSearchBuilder(conditions)
                .select("count(id)");
        return getNamedParameterJdbcTemplate().queryForList(builder.getSQL(),
                conditions, Integer.class).stream().findFirst().orElse(0);
    }

    @Override
    public List<Map<String, Object>> searchMembers(Map<String, Object> conditions, OrderBy orderBy, int start, int limit) {
        DynamicQueryBuilder builder = this.createGroupMemberSearchBuilder(conditions)
                .select("*")
                .orderBy(orderBy)
                .setFirstResult(start)
                .setMaxResults(limit);

        return getNamedParameterJdbcTemplate().queryForList(builder.getSQL(), conditions);
    }

    @Override
    public Map<String, Object> getMemberByGroupIdAndUserId(Integer groupId, Integer userId) {
        String sql = String.format("SELECT * FROM %s WHERE groupId=? and userId=? LIMIT 1", TABLE_NAME);
        return getJdbcTemplate().queryForList(sql, groupId, userId).stream().findFirst().orElse(new HashMap<>(0));
    }

    private DynamicQueryBuilder createGroupMemberSearchBuilder(Map<String, Object> conditions) {
        return new DynamicQueryBuilder(conditions)
                .from(TABLE_NAME)
                .andWhere("groupId = :groupId")
                .andWhere("role = :role")
                .andWhere("userId = :userId");
    }
}
